package com.ljs.liojbackendquestionservice.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljs.libackendmodel.model.dto.questionsubmit.QuestionQuerySubmitRequest;
import com.ljs.libackendmodel.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.ljs.libackendmodel.model.entity.QuestionSubmit;
import com.ljs.libackendmodel.model.entity.User;
import com.ljs.libackendmodel.model.enums.QuestionSubmitLanguageEnum;
import com.ljs.libackendmodel.model.enums.QuestionSubmitStatusEnum;
import com.ljs.libackendmodel.model.vo.QuestionSubmitVO;
import com.ljs.liojbackendcommon.common.ErrorCode;
import com.ljs.liojbackendcommon.constant.CommonConstant;
import com.ljs.liojbackendcommon.exception.BusinessException;
import com.ljs.liojbackendcommon.utils.SqlUtils;
import com.ljs.liojbackendquestionservice.mapper.QuestionSubmitMapper;
import com.ljs.liojbackendquestionservice.rabbitmq.MyMessageProducer;
import com.ljs.liojbackendquestionservice.service.QuestionService;
import com.ljs.liojbackendquestionservice.service.QuestionSubmitService;
import com.ljs.liojbackendserviceclient.service.JudgeFeignClient;
import com.ljs.liojbackendserviceclient.service.UserFeignClient;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author 李
 * @description 针对表【question_submi  t(题目提交表)】的数据库操作Service实现
 * @createDate 2025-02-06 16:19:00
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {
    @Resource
    private MyMessageProducer myMessageProducer;
    @Resource
    private QuestionService questionService;
    @Resource
    private UserFeignClient userFeignClient;
    @Resource
    @Lazy
    private JudgeFeignClient judgeFeignClient;

    /**
     * 提交
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public Long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //  校验编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        // 判断实体是否存在，根据类别获取实体
        Long questionId = questionSubmitAddRequest.getQuestionId();
        if (questionId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交
        long userId = loginUser.getId();
        // 每个用户串行提交
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(questionSubmitAddRequest.getLanguage());
        // 设置提交状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        Boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据库插入失败");
        }

        //todo  判题
        Long questionSubmitId = questionSubmit.getId();
        //发送消息
        myMessageProducer.send("code_exchange", "my_routingKey", String.valueOf(questionSubmitId));
//        CompletableFuture.runAsync(()->{
//
//                    judgeFeignClient.doJudge(questionSubmitId);
//        });

        return questionSubmitId;
    }

    /**
     * 获取查询包装类（用户根据哪些字段进行查询，根据前端请求对象，得到mybatis能够查询的QueryWrapper包装类）
     *
     * @param questionQuerySubmitRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionQuerySubmitRequest questionQuerySubmitRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionQuerySubmitRequest == null) {
            return queryWrapper;
        }
        Long questionId = questionQuerySubmitRequest.getQuestionId();
        String language = questionQuerySubmitRequest.getLanguage();
        Integer status = questionQuerySubmitRequest.getStatus();
        Long userId = questionQuerySubmitRequest.getUserId();
        String sortField = questionQuerySubmitRequest.getSortField();
        String sortOrder = questionQuerySubmitRequest.getSortOrder();
        //拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);

        //todo 判题

        return queryWrapper;
    }


    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //脱敏:仅管理员能够看见自己（提交的userId登录 userId不同）提交的代码和答案

        Long userId = loginUser.getId();
        //处理脱敏
        if (userId != questionSubmit.getUserId() && !userFeignClient.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().
                map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());

        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
        //todo 理解这段代码
//        // 1. 关联查询用户信息
//        Set<Long> userIdSet = questionSubmitList.stream().map(QuestionSubmit::getUserId).collect(Collectors.toSet());
//        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
//                .collect(Collectors.groupingBy(User::getId));
//        // 填充信息
//        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
//            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
//            Long userId = questionSubmit.getUserId();
//            User user = null;
//            if (userIdUserListMap.containsKey(userId)) {
//                user = userIdUserListMap.get(userId).get(0);
//            }
//            questionSubmitVO.setUserVO(userService.getUserVO(user));
//            return questionSubmitVO;
//        }).collect(Collectors.toList());

    }


}




